package com.itstyle.seckill.web;

import com.itstyle.seckill.common.entity.Result;
import com.itstyle.seckill.common.entity.Seckill;
import com.itstyle.seckill.common.utils.HttpClient;
import com.itstyle.seckill.common.utils.IPUtils;
import com.itstyle.seckill.queue.activemq.ActiveMQSender;
import com.itstyle.seckill.service.ISeckillService;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import org.apache.activemq.command.ActiveMQQueue;

@Api(tags = "秒杀商品")
@RestController
@RequestMapping("/seckillPage")
public class SeckillPageController {

    @Autowired
    private ISeckillService seckillService;

    @Autowired
    private ActiveMQSender activeMQSender;

    @Autowired
    private HttpClient httpClient;
    @Value("${qq.captcha.url}")
    private String url;
    @Value("${qq.captcha.aid}")
    private String aid;
    @Value("${qq.captcha.AppSecretKey}")
    private String appSecretKey;


    @ApiOperation(value = "秒杀商品列表", nickname = "小柒2012")
    @PostMapping("/list")
    public Result list() {
        //返回JSON数据、前端VUE迭代即可
        List<Seckill> List = seckillService.getSeckillList();
        return Result.ok(List);
    }

    @RequestMapping("/startSeckill")
    public Result startSeckill(String ticket, String randstr, HttpServletRequest request, HttpServletResponse response) {

        try {
            //cred 第一个参数 SecretId  第二个参数SecretKey 在腾讯云秘钥获取
            Credential cred = new Credential("AKIDUnreAPP8bnyvb080bYFgqjLglY4JHyOX", "vay6xYrte8LHvJPEm22lDOJxKQGo55nF");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("captcha.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            CaptchaClient client = new CaptchaClient(cred, "", clientProfile);

            DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
            req.setAppSecretKey(appSecretKey);  //用于服务器端校验验证码票据的验证密钥，请妥善保密，请勿泄露给第三方
            req.setCaptchaAppId(Long.valueOf(aid)); //验证码应用ID
            req.setCaptchaType(9L);    //固定填值：9。可在控制台配置不同验证码类型。
            req.setUserIp(IPUtils.getIpAddr(request)); //用户操作来源的外网 IP
            req.setTicket(ticket);  //前端回调函数返回的用户验证票据
            req.setRandstr(randstr);  //前端回调函数返回的随机字符串

            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            // logger.info("验证图形验证码是否正确返回" + DescribeCaptchaResultResponse.toJsonString(resp));
            if (1==(resp.getCaptchaCode())) {
                //进入队列、假数据而已
                Destination destination = new ActiveMQQueue("seckill.queue");
                activeMQSender.sendChannelMess(destination, 1000 + ";" + 1);
                return Result.ok();
            } else {
                return Result.error("验证失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            // logger.error("验证图形验证码是否正确失败" + e.getMessage());
            return Result.error("验证失败");
        }

    }
//	@RequestMapping("/startSeckill")
//    public Result  startSeckill(String ticket,String randstr,HttpServletRequest request) {
//        HttpMethod method =HttpMethod.POST;
//        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
//        params.add("aid", aid);
//        params.add("AppSecretKey", appSecretKey);
//        params.add("Ticket", ticket);
//        params.add("Randstr", randstr);
//        params.add("UserIP", IPUtils.getIpAddr(request));
//		params.add("CaptchaType","9L");
//        String msg = httpClient.client(url,method,params);
//        /**
//         * response: 1:验证成功，0:验证失败，100:AppSecretKey参数校验错误[required]
//         * evil_level:[0,100]，恶意等级[optional]
//         * err_msg:验证错误信息[optional]
//         */
//        //{"response":"1","evil_level":"0","err_msg":"OK"}
//        JSONObject json = JSONObject.parseObject(msg);
//        String response = (String) json.get("response");
//        if("1".equals(response)){
//        	//进入队列、假数据而已
//        	Destination destination = new ActiveMQQueue("seckill.queue");
//        	activeMQSender.sendChannelMess(destination,1000+";"+1);
//        	return Result.ok();
//        }else{
//        	return Result.error("验证失败");
//        }
//    }
}
